package light.head.dao.oa;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.Contract;

@Service
public class ContractDAO extends BaseDAO<Contract, Integer>{

	private final static String sql_findlast = "FROM Contract c WHERE c.oc = ? AND c.cu = ? ORDER BY c.code DESC";
	private final static String sql_findByUuid = "FROM Contract c WHERE c.uuid = ? AND c.deleted = 0";
	
	public RESULT findByMap(Map<String, String> map, PageBean pb) {
		StringBuffer hql = new StringBuffer("FROM Contract c WHERE 1=1");
		List<Object> list = null;
		if(null != map) {
			list = new ArrayList<Object>();
			String name = map.get(Parm.NAME);
			String start = map.get(Parm.START);
			String end = map.get(Parm.END);
			String cuname = map.get(Parm.CUNAME);
			String tname = map.get(Parm.TNAME);
			String oc = map.get(Parm.OC);
			if(isNotNull(name)) {
				hql.append(" AND c.name like ?");
				list.add("%" + name + "%");
			}if(isNotNull(start)) {
				hql.append(" AND c.end < ?");
				list.add(DateUtils.getDateByStr(start, "yyyy-MM-dd"));
			}if(isNotNull(end)) {
				hql.append(" AND c.end > ?");
				list.add(DateUtils.getDateByStr(end, "yyyy-MM-dd"));
			}if(isNotNull(cuname)) {
				hql.append(" AND c.uc in (SELECT u.code FROM UserInfo u WHERE u.realName like ?)");
				list.add("%" + cuname + "%");
			}if(isNotNull(tname)) {
				hql.append(" AND c.tc IN (select c.code FROM Contract c WHERE c.name like ?)");
				list.add("%" + tname + "%");
			}if(isNotNull(oc)) {
				hql.append(" AND c.oc = ?");
				list.add(Integer.parseInt(oc));
			}
			hql.append(" AND ( c.deleted = 0 OR c.deleted = null)");
			hql.append(" ORDER BY c.code DESC");
		}
		if(findToPageBean(hql.toString(), pb, list) == RESULT.SUCCESS) {
			return RESULT.SUCCESS;
		}
		
		return RESULT.ERROR;
	}

	

	public RESULT update(Contract con) {
		if(null == con || null == con.getCode()) {
			return RESULT.PARAMETER_ERROR;
		}
		Contract old = get(con.getCode());
		if(null == old){
			return RESULT.NOT_FIND;
		}
		if(isNotNull(con.getName())) {
			old.setName(con.getName());
		}if(null != con.getDeleted()) {
			old.setDeleted(con.getDeleted());
		}if(null != con.getTc()) {
			old.setTc(con.getTc());
		}if(null != con.getEnd()) {
			old.setEnd(con.getEnd());
		}
		
		RESULT result = upd(old);
		
		return result;
	}
	
	public Integer findLastCode(Integer oc, Integer cu) {
		List<Contract> list = findI(sql_findlast, oc, cu);
		return list.get(0).getCode();
	}
	
	public Contract findByUuid(String uuid) {
		List<Contract> list = find(sql_findByUuid, uuid);
		return list.get(0);
	}
}
